import {NativeEventEmitter, NativeModules} from 'react-native';

const module = NativeModules.SerialPortModule;
const emitter = new NativeEventEmitter(module);
let callback = null;
const SerialPortModule = {
  scanDevices(cb) {
    module &&
      module.scanDevices(id => {
        cb && cb(id);
      });
  },
  async connectDevice(deviceName, onMessageSend, onMessageReceived) {
    emitter.addListener('onMessageSend', data => {
      onMessageSend && onMessageSend(data.data);
    });
    emitter.addListener('onMessageReceived', data => {
      onMessageSend && onMessageReceived(data.data);
      callback && callback(data.data);
      callback = null;
    });
    return (await module) && module.connectDevice(deviceName);
  },

  openAll(address, onMessageReceived) {
    callback = onMessageReceived;
    module && module.openAll(address);
  },
  openLock(address, lock, onMessageReceived) {
    callback = onMessageReceived;
    module && module.openLock(address, lock);
  },
  checkAll(address, onMessageReceived) {
    callback = onMessageReceived;
    module && module.checkAll(address);
  },
  checkLock(address, lock, onMessageReceived) {
    callback = onMessageReceived;
    module && module.checkLock(address, lock);
  },
};

export default SerialPortModule;
